//
//  LcAudioCenter.m
//  18Birdies
//
//  Created by Lc on 15/7/30.
//  Copyright (c) 2015年 Lc. All rights reserved.
//

#import <AVFoundation/AVFoundation.h>

#import "LcAudioCenter.h"
#import "LcPreconditions.h"

@interface LcAudioCenter ()
@property(nonatomic, strong) NSMutableDictionary* players;
@end

@implementation LcAudioCenter

- (void)internalInit {
  self.players = [NSMutableDictionary dictionary];
}

- (void)play:(NSString*)audioFile {
  LC_CHECK_NOT_EMPTY(audioFile);
#if TARGET_OS_SIMULATOR
// do not play audio on simulator
#else
  // set audioSession everytime because taking vedio may change the audio setting by iOS system
  AVAudioSession* audioSession = [AVAudioSession sharedInstance];
  [audioSession setCategory:AVAudioSessionCategoryAmbient
                withOptions:AVAudioSessionCategoryOptionMixWithOthers
                      error:nil];

  AVAudioPlayer* player = self.players[audioFile];
  if (player == nil) {
    NSString* filePath =
        [[NSBundle mainBundle] pathForResource:audioFile ofType:nil];
    if (filePath.length == 0) {
      return;
    }
    NSURL* url = [NSURL fileURLWithPath:filePath];
    @try {
      player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    } @catch (NSException *exception) {
    }
    if (player != nil) {
      [player prepareToPlay];
      self.players[audioFile] = player;
    } else {
      return;
    }
  }
  LC_CHECK_NOT_NULL(player);
  if (!player.playing) {
    [player play];
  }
#endif
}

@end
